package groupchat.client;

import com.alibaba.fastjson.JSONObject;
import groupchat.entities.ClientMessage;
import groupchat.server.NettyServer;
import groupchat.server.ServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;


public class NettyClient {
    private static String host = "127.0.0.1";
    private static int port = 8080;

    public static void main(String[] args) throws Exception{
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast("decoder", new StringDecoder());
                        pipeline.addLast("encoder", new StringEncoder());
                        pipeline.addLast(new ClientHandler());
                    }
                });

        ChannelFuture server = bootstrap.connect(host, port).sync();
        System.out.println("客户端已启动。。。。。");
        Channel serverChannel = server.channel();

        Scanner scanner = new Scanner(System.in);
        System.out.println("请问您的姓名是？");
        String senderName = scanner.nextLine();
        while(true) {
            System.out.println("请问您想发送的消息是？");
            String text = scanner.nextLine();
            System.out.println("请问是群发嘛");
            Integer type = null;
            if(scanner.nextLine().equals("Y")) {
                type = ServerHandler.RADIO;
                send(serverChannel,senderName,null,type,text);
            }else {
                type = ServerHandler.ALONE;
                System.out.println("请问发给谁？");
                String receiver = scanner.nextLine();
                send(serverChannel,senderName,receiver,type,text);
            }
        }
    }

    public static void send(Channel channel,String sender, String receiver, int type, String text) {
        channel.writeAndFlush(JSONObject.toJSONString(new ClientMessage(sender, type, receiver, text)));
        System.out.println("发送成功");
    }
}
